<template>
  <div class="mapWrap">
    <div ref="mapRef" id="container" class="map"></div>
    <info v-if="infoVisible" :infoData="infoData" :position="infoPostion" @onClose="handleClose"></info>
  </div>
</template>

<script setup name="gMap">
  import info from '../info/index.vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import cameraNormal from '@/assets/image/camera_normal.png';

  import { shallowRef, ref, onUnmounted, reactive, watch, onMounted } from 'vue';
  const props = defineProps(['mapData', 'checkedKeys', 'selectedKeys', 'name', 'id', 'children', 'lngLat']);
  let mapRef = ref(null);
  let infoVisible = ref(false);
  let map = shallowRef(null);
  let AMap = shallowRef(null);
  let infoPostion = null;
  let infoData = null;
  //存储marker，删除的时候用
  let markerData = {};
  /** load */
  const loadMap = () => {
    AMapLoader.load({
      key: 'f599beada738982465764ddd0b1dae4e',
      version: '2.0',
      plugins: ['AMap.ControlBar', 'AMap.ToolBar', 'AMap.ElasticMarker']
    })
      .then(aMap => {
        AMap = aMap;
        createMap(aMap, props.mapData[0][props.lngLat].split(','));
      })
      .catch(e => {
        console.log(e);
      });
  };
  const handleClose = value => {
    infoVisible.value = value;
  };
  /** create */
  const createMap = (AMap, center) => {
    map = new AMap.Map(mapRef.value, {
      mapStyle: 'amap://styles/normal', //设置地图的显示样式
      features: ['road', 'point', 'bg', 'building'], // ['road', 'point', 'bg', 'building']
      rotateEnable: true,
      pitchEnable: true,
      zoom: 17, //zoom可设范围：[2,20]
      pitch: 50,
      rotation: -15,
      viewMode: '3D', //设置地图模式 2D 3D
      //terrain: true, // 开启地形图
      zooms: [15, 20],
      center
    });
    addMapTools(map, AMap);
    //addMapMarker(map, AMap);
    handleEvent(map, AMap);
    map.on('complete', () => {
      mapRef.value.removeChild(mapRef.value.querySelector('.amap-logo'));
      mapRef.value.removeChild(mapRef.value.querySelector('.amap-copyright'));
    });
    onUnmounted(() => {
      map.destroy();
    });
  };
  /** tools */
  const addMapTools = (map, AMap) => {
    const controlBar = new AMap.ControlBar({
      position: {
        right: '10px',
        top: '10px'
      }
    });
    controlBar.addTo(map);
    const toolBar = new AMap.ToolBar({
      position: {
        right: '40px',
        top: '110px'
      }
    });
    toolBar.addTo(map);
  };
  /** marker */
  const addMapMarker = (data, map, AMap) => {
    let markerArr = [];
    data.forEach(item => {
      let lngLat = item[props.lngLat].split(',');
      let marker = new AMap.Marker({
        size: new AMap.Size(64, 71), //图标尺寸
        offset: new AMap.Pixel(-5, -30),
        anchor: 'center',
        imageSize: new AMap.Size(64, 71), //根据所设置的大小拉伸或压缩图片
        position: new AMap.LngLat(...lngLat), // 经纬度对象，也可以是经纬度构成的一维数组
        title: '北京',
        icon: cameraNormal
      });
      marker.on('click', ev => {
        const { x, y } = ev.pixel;
        infoPostion = { x, y };
        infoData = item;
        infoVisible.value = true;
      });
      markerArr.push(marker);
      markerData[item[props.id]] = marker;
    });
    map.add(markerArr);
  };
  /** handleEvent */
  const handleEvent = () => {
    //响应地图点击事件的回调
    map.on('click', function (ev) {
      // 触发事件的对象
      let target = ev.target;
      // 触发事件的地理坐标，AMap.LngLat 类型
      let lnglat = ev.lnglat;
      // 触发事件的像素坐标，AMap.Pixel 类型
      let pixel = ev.pixel;
      // 触发事件类型
      let type = ev.type;
    });
    map.on('zoomend', function (ev) {
      console.log(map.getZoom());
    });
  };

  /** 监听checkedKeys的变化，增加或者删除标记点 */
  watch(
    () => props.checkedKeys,
    (newkeys, oldKeys) => {
      //传过来的keys永远是选中的，包含组的key
      if (newkeys.length > oldKeys.length) {
        //增加
        let data = difference([...newkeys], [...oldKeys]);
        const addData = [];
        data.forEach(key => {
          const findItem = props.mapData.find(fItem => fItem[props.id] == key);
          findItem && addData.push(findItem);
        });
        addMapMarker(addData, map, AMap);
      } else {
        //取消
        let data = difference([...oldKeys], [...newkeys]);
        data.forEach(key => {
          if (markerData[key]) {
            map.remove(markerData[key]);
            delete markerData[key];
          }
        });
      }
    }
  );
  //监听selectedKeys的变化，设置地图的中心点位置
  watch(
    () => props.selectedKeys,
    newKeys => {
      if (newKeys.length) {
        let key = newKeys[0];
        let findItem = props.mapData.find(item => item[props.id] == key);
        map.setCenter(findItem[props.lngLat].split(','));
      }
    }
  );
  const difference = (arr1, arr2) => {
    return arr1.concat(arr2).filter(e => arr1.includes(e) && !arr2.includes(e));
  };
  onMounted(() => {
    loadMap();
  });
</script>

<style lang="less" scoped>
  .mapWrap {
    height: 100%;
  }
  .map {
    height: 100%;
  }
</style>
